package com.example.myblog.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class PasswordUtils {
    /*
        随机盐值加密
     */
    public static String encrypt(String password) {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String saltPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        return salt + "$" + saltPassword;
    }

    /*
        固定盐值加密
     */
    public static String encrypt(String password, String salt) {
        String saltPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        return salt + "$" + saltPassword;
    }

    /*
        密码校验
     */
    public static boolean check(String inputPassword, String finalPassword) {
        if (StringUtils.hasLength(inputPassword) && StringUtils.hasLength(finalPassword) &&
                finalPassword.length() == 65) {
            String salt = finalPassword.split("\\$")[0];
            String confirmPassword = encrypt(inputPassword, salt);
            return confirmPassword.equals(finalPassword);
        }
        return false;
    }
}
